package com.alveole.events;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.alveole.tools.Logger;

public abstract class BrowserEvent extends Event {

	protected HashMap<String,String> parameters = null;
	protected EventBean eventBean;

	public void init(EventBean eventBean)
	{
		init(eventBean.command,eventBean.target,eventBean.data);
		this.eventBean=eventBean;
		
	}
	
	public abstract List<ServerEvent> getAnswers_();
	public List<ServerEvent> getAnswers() 
	{
		setParameters();
		return getAnswers_();
	}
	private String URLDecode(String value)
	{
		String r = null;
		try {
			r=URLDecoder.decode(value,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return r;
	}
	private void setParameters() 
	{
		
		parameters = new HashMap<String,String>() ;
		if (!StringUtils.isEmpty(data))
		{
			String [] entries = data.split("&");
			for (String entry : entries)
			{
				String [] value = entry.split("=");
				parameters.put(value[0],value.length>1 ? URLDecode(value[1]) : "");
			}
		}
	}
	public static BrowserEvent getEvent(EventBean eventBean)
	{
		BrowserEvent event=null;
		try {
			@SuppressWarnings("unchecked")
			Class<BrowserEvent> eventClass = (Class<BrowserEvent>) Class.forName(Event.class.getPackage().getName()+".Browser"+eventBean.command+"Event");
			event = eventClass.newInstance();
			event.init(eventBean);
		} catch (ClassNotFoundException e) {
			Logger.log(Logger.ERROR,"Cannot find interpreter for command : " + eventBean.command);
				event=new BrowserUnknownCommandEvent(eventBean.command);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return event;
	}
	public static List<ServerEvent> process(EventBean eventBean)
	{
		BrowserEvent event = BrowserEvent.getEvent(eventBean);
		return event.getAnswers();
	}
  	
}
